from django.contrib.contenttypes.models import ContentType
from django.db.models import Q
from rest_framework.decorators import action
from rest_framework.mixins import UpdateModelMixin
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.viewsets import ReadOnlyModelViewSet, ModelViewSet

# ReadOnlyModelViewSet  只含有List和Retrieve两种视图
from meiduo_admin.serializer.orders import OrdersListSerializer, OrderDetailSerializer, OrderStatusSerializer
from orders.models import OrderInfo


class OrdersViewSet(UpdateModelMixin,ReadOnlyModelViewSet):
    permission_classes = [IsAdminUser]

    def get_queryset(self):
        keyword = self.kwargs.get('keyword')
        # keyword=self.request.query_params.get('keyword')  # 这种方法也可以
        if keyword:
            value = OrderInfo.objects.filter(Q(order__contains=keyword) |
                                             Q(skus__sku__name__contains=keyword))
        else:
            value = OrderInfo.objects.all()
        return value

    def get_serializer_class(self):
        if self.action == 'list':
            return OrdersListSerializer
        elif self.action == 'retrieve':
            return OrderDetailSerializer
        else:
            return OrderStatusSerializer

    @action(methods=['put'],detail=True)
    def status(self,request,pk):
        """
        修改订单状态:
        1. 校验订单是否有效
        2. 获取订单状态status并校验(status必传，status是否合法)
        3. 修改并保存订单的状态
        4. 返回应答
        """
        # instance=self.get_object()  #   get_object方法会查询参数中的主键为pk的对象_
        # # instance=OrderInfo.objects.get(id=pk)
        # serializer=OrderStatusSerializer(instance,data=request.data)
        # serializer.is_valid(raise_exception=True)
        # serializer.save()
        #
        # return Response(serializer.data)

        return self.update(request,pk)


# class OrderDetailViewSet(ModelViewSet):
#     permission_classes = [IsAdminUser]
#
